﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Xml;
using MinhTuan;
using System.Data;
using System.Data.SqlClient;

namespace News
{
    public  class ITgateVN
    {

        #region Variables

        private const String Host = "itgate.com.vn";
        private const String RssNodeEx = "rss/channel/item";
        private const String TitleEx = "title";
        private const String DescriptionEx = "description";
        private const String LinkEx = "link";
        private const String PubDateEx = "pubDate";
        private const String XmlResourceLink = "data/xmlresource/resource.xml";
        private const String PrintPage = "http://itgate.com.vn/printpage.aspx?i";
        
        #endregion
       
        #region Public Method

        public static NewsItem GetNewsResource(RssItem myRssItem, Int16 ChannelId, string ChannelName, string ChannelTitle)
        {
            NewsItem myNewsItem = new NewsItem();
            //try
            //{
                String ResourceURL = myRssItem.URL;
                Int32 Index = ResourceURL.LastIndexOf("id=");
                String printResource = PrintPage + ResourceURL.Remove(0, Index);
                HtmlDocument MyHtmlDocument = RssFeed.GetWebResource(printResource);
                if (MyHtmlDocument != null)
                {
                    string author = "Pham Minh Tuan"; string details = ""; string image = ""; Int32 tblIndex = 0; Int32 tblendIndex = 0; 
                    
                    //Get news author
                    HtmlNode NewsAuthor = MyHtmlDocument.DocumentNode.SelectSingleNode("//div[@class = \"author\"]");
                    if (NewsAuthor != null)
                    {
                        author = NewsAuthor.InnerText;
                        if (tblIndex > -1 && tblendIndex > -1)
                        {
                            tblIndex = author.IndexOf("(");
                            tblendIndex = author.IndexOf(")");
                            author = "Minh Tuan " + author.Substring(tblIndex);
                        }
                    }

                    //Get news image
                    HtmlNode imageNode;
                    imageNode = MyHtmlDocument.DocumentNode.SelectSingleNode("//div[@class = \"content\"]/p/table//img");
                    if (imageNode != null)
                    { 
                        image = "http://www.itgate.com.vn/" + imageNode.Attributes["src"].Value;
                        imageNode.RemoveAll();
                    }
                    else
                    {
                        imageNode = MyHtmlDocument.DocumentNode.SelectSingleNode("//div[@class = \"content\"]/p//img");
                        if (imageNode != null)
                        {
                            image = "http://www.itgate.com.vn/" + imageNode.Attributes["src"].Value;
                            imageNode.RemoveAll();
                        }
                        else
                        {
                            imageNode = MyHtmlDocument.DocumentNode.SelectSingleNode("//div[@class = \"content\"]/div//img");
                            if (imageNode != null)
                            {
                                image = "http://www.itgate.com.vn/" + imageNode.Attributes["src"].Value;
                                imageNode.RemoveAll();
                            }
                            else
                            {
                                imageNode = MyHtmlDocument.DocumentNode.SelectSingleNode("//div[@class = \"content\"]//img");
                                if (imageNode != null)
                                {
                                    image = "http://www.itgate.com.vn/" + imageNode.Attributes["src"].Value;
                                    imageNode.RemoveAll();
                                }
                            }
                        }
                    }

                    // Get news details
                    HtmlNode myContentNode = MyHtmlDocument.DocumentNode.SelectSingleNode("//div[@class = \"content\"]");
                    if (myContentNode != null) { details = myContentNode.InnerHtml; }
                  
                    tblIndex = details.IndexOf("<table");
                    tblendIndex = details.IndexOf("</table>") + 8;
                    details = details.Replace("<img alt=\"itGatevn","<img alt=\"Minh Tuan");
                    if (tblIndex > -1 && tblendIndex > -1) { details = details.Remove(tblIndex, tblendIndex - tblIndex); }
                    details = details.Replace("src=\"pictures/web", "src=\"http://www.itgate.com.vn/pictures/web");
                    details = details.Replace("src=\"/pictures/web", "src=\"http://www.itgate.com.vn/pictures/web");
                    details = details.Replace("<img>","");
                    myNewsItem = new NewsItem(myRssItem.Title,  myRssItem.URL,  myRssItem.Description, details.Trim(), author, Convert.ToDateTime(myRssItem.pubDate ),  image, ChannelId, ChannelName, ChannelTitle);
                }
                return myNewsItem;
            //}
            //catch (Exception ex)
            //{
            //    myNewsItem = new NewsItem(myRssItem.Title, myRssItem.Description, ex.Message, "", Convert.ToDateTime(myRssItem.pubDate), "", ChannelId, ChannelName, ChannelTitle);
            //    return myNewsItem;
            //}

        }
        public static String GetTintuc()
        {
            string file = "http://itgate.com.vn/printpage.aspx?iid=52668";
            HtmlDocument node= RssFeed.GetWebResource(file);
            HtmlNode content=node.DocumentNode.SelectSingleNode("//div[@class=\"content\"]");
            String detail = content.InnerHtml;
            HtmlNode NewsAuthor = node.DocumentNode.SelectSingleNode("//div[@class = \"author\"]");
            HtmlNode chi=node.DocumentNode.SelectSingleNode("//div[@class = \"content\"]/p//img");
            string image="www.itgate.com.vn"+chi.Attributes["src"].Value;
            detail = detail.Replace("src=\"/pictures/web", "src=\"http://www.itgate.com.vn/pictures/web");
            String anh = chi.InnerHtml;
            return anh;
        }
         public static List<NewsItem> GetLastestNewsFromRSS(string Channel, string RssChannel, String ChannelExpression)
        { 
            List<NewsItem> myLastestNews = new List<NewsItem>();
            try 
            {
                List<RssItem> myLastestRssItems = RssFeed.GetRssItems(Host, Channel, RssChannel, RssNodeEx, TitleEx, DescriptionEx, LinkEx, PubDateEx, XmlResourceLink, ChannelExpression);
                NewsItem myNewsItem;
                foreach (RssItem myRssItem in myLastestRssItems)
                {
                    myNewsItem = GetNewsResource(myRssItem,1,"","");
                    myLastestNews.Add(myNewsItem);
                }
                return myLastestNews;
            }
            catch (Exception)
            {
                return myLastestNews;
            }
        
        }

        public static List<NewsItem> GetLastestNews(string Channel)
        {
            List<NewsItem> myLastestNews = new List<NewsItem>();
            try
            {
                RssFeed myLastestRssItems = RssFeed.GetActiveRssFeedItems(Host, Channel,RssNodeEx, TitleEx, DescriptionEx, LinkEx, PubDateEx, XmlResourceLink);
                NewsItem myNewsItem;
                foreach (RssItem myRssItem in myLastestRssItems.Items)
                {
                    myNewsItem = GetNewsResource(myRssItem, myLastestRssItems.ChannelId, myLastestRssItems.ChannelName, myLastestRssItems.ChannelTitle);
                   if (myNewsItem.Details.Trim().Length > 0)
                   {
                        myLastestNews.Add(myNewsItem);
                   }
                   
                }
                return myLastestNews;
            }
            catch (Exception)
            {
                return myLastestNews;
            }

        }

        public static List<NewsItem> GetLastestNews()
        {
            List<NewsItem> myLastestNews = new List<NewsItem>();
            try
            {
                XmlDocument myResourceDocument = new XmlDocument();
                String RightResourceFilePath = System.Web.HttpContext.Current.Server.MapPath(XmlResourceLink);
                myResourceDocument.Load(RightResourceFilePath);
                XmlNode myRoot = myResourceDocument.SelectSingleNode("//Tintuc");
                foreach (XmlNode myTemp in myRoot) 
                {
                    String Channel = myTemp.Name.ToString();
                    RssFeed myLastestRssItems = RssFeed.GetActiveRssFeedItems(Host, Channel, RssNodeEx, TitleEx, DescriptionEx, LinkEx, PubDateEx, myResourceDocument, RightResourceFilePath);
                    NewsItem myNewsItem;
                    foreach (RssItem myRssItem in myLastestRssItems.Items)
                    {
                        myNewsItem = GetNewsResource(myRssItem, myLastestRssItems.ChannelId, myLastestRssItems.ChannelName, myLastestRssItems.ChannelTitle);
                        if (myNewsItem.Details.Trim().Length > 0)
                        {
                            myLastestNews.Add(myNewsItem);
                        }
                    }
                }
                return myLastestNews;
            }
            catch (Exception)
            {
                return myLastestNews;
            }

        }

        public static Int32 SaveLastestNews( String Lang)
        {
            Access myAccess = new Access();
            Int16 Result = 0; Int32 TotalResult = 0;
            //try
            //{
                List<NewsItem> LastestNews  = GetLastestNews();
                if (LastestNews.Count > 0)
                {
                    Access.InitAccess();
                    foreach (NewsItem myItem in LastestNews)
                    {
                        String Title = Access.RemoveVietnameseSigns(myItem.Name);
                        String PostString = Access.GetDateString(myItem.PostDate, Lang);
                        Access.mySqlCommand.Parameters.Clear();
                        Access.mySqlCommand.CommandText = "Sp_AddNewsItem";
                        Access.mySqlCommand.Parameters.Add("@Lang_id", SqlDbType.NChar).Value = Lang;
                        Access.mySqlCommand.Parameters.Add("@Item_Name", SqlDbType.NVarChar).Value = myItem.Name;
                        Access.mySqlCommand.Parameters.Add("@Item_Title", SqlDbType.NVarChar).Value = Title;
                        Access.mySqlCommand.Parameters.Add("@Item_Summary", SqlDbType.NVarChar).Value = myItem.Summary;
                        Access.mySqlCommand.Parameters.Add("@Item_Details", SqlDbType.NText).Value = myItem.Details;
                        Access.mySqlCommand.Parameters.Add("@Item_Author", SqlDbType.NVarChar).Value = myItem.Author;
                        Access.mySqlCommand.Parameters.Add("@Item_PostDate", SqlDbType.SmallDateTime).Value = myItem.PostDate;
                        Access.mySqlCommand.Parameters.Add("@Item_PostString", SqlDbType.NVarChar).Value = PostString;
                        Access.mySqlCommand.Parameters.Add("@Item_Image", SqlDbType.NVarChar).Value = myItem.Image;
                        Access.mySqlCommand.Parameters.Add("@Item_ImageDescription", SqlDbType.NVarChar).Value = myItem.Name;
                        Access.mySqlCommand.Parameters.Add("@Item_Keyword", SqlDbType.NVarChar).Value = myItem.Name + ", " + myItem.CatalogName + ", " + myItem.Summary;
                        Access.mySqlCommand.Parameters.Add("@Category_Id", SqlDbType.TinyInt).Value = myItem.CatalogId;
                        Access.mySqlCommand.Parameters.Add("@Category_Title", SqlDbType.NVarChar).Value = myItem.CatalogTitle;
                        Access.mySqlCommand.Parameters.Add("@Category_Name", SqlDbType.NVarChar).Value = myItem.CatalogName;
                        Access.mySqlCommand.Parameters.Add("@IsHot", SqlDbType.NVarChar).Value = false;
                        Access.mySqlCommand.Parameters.Add("@IsActive", SqlDbType.NVarChar).Value = true;

                        Result = Convert.ToInt16(Access.mySqlCommand.ExecuteNonQuery());
                        if (Result == 1)
                        {
                            TotalResult += 1;
                        }
                    }
                    Access.ClosedAccess();
                }
              return TotalResult;

            //}
            //catch (Exception)
            //{
            //    Access.ClosedAccess();
            //    return TotalResult;
            //}

        
        }

        #endregion

    }
}

